import { FormFieldWrapper } from '@components/common/formFieldWrapper/formFieldWrapper'
import { ReactComponentExt } from '@helpers/ReactExt'
import { GlobalStoreModel } from '@store/globalStore'
import { BaseProps, ComponentStore } from '@store/store'
import { Button, Card, Col, Empty, Form, List, Row } from 'antd'
import { FormComponentProps } from 'antd/lib/form'
import { configs } from 'config'
import { inject, observer } from 'mobx-react'
import * as React from 'react'
import * as styles from './studentDetail.less'

const formFieldConfigs: FieldInter[] = [
  {
    rule: [{ message: '请上传图片影集', required: true }],
    type: 'upload',
    label: '个人图片影集',
    field: 'dspPicturePhotos',
    placeholder: '请上传图片影集',
    acceptType: 'image/*',
    count: 2
  },
  {
    type: 'upload',
    label: '个人视频影集',
    field: 'dspPictureVideos',
    placeholder: '请上传视频影集 ',
    acceptType: 'video/*',
    count: 2
  },
  {
    type: 'textarea',
    label: '老师评估',
    field: 'evaluate',
    placeholder: '请输入老师评估'
  }
]

export interface StudentDetailProps extends BaseProps, FormComponentProps {
  globalStore: GlobalStoreModel
}

interface StudentDetailState {
  pictureList: string[]
  videoList: string[]
}

@inject((store: ComponentStore) => {
  return { globalStore: store.globalStore }
})
@observer
class StudentDetail extends ReactComponentExt<StudentDetailProps, StudentDetailState> {
  private studentId!: number
  private pictureList: string[] = []
  private videoList: string[] = []
  public init(): void {
    this.state = {
      pictureList: [],
      videoList: []
    }
    const { studentId } = this.query
    this.studentId = studentId
    this.handleFormCancel = this.handleFormCancel.bind(this)
    this.handleFormSubmit = this.handleFormSubmit.bind(this)
  }

  public componentDidMount() {
    this.getStudentWorks()
  }

  public render() {
    const { form } = this.props
    const { pictureList, videoList } = this.state
    return (
      <div className={styles.wrapper}>
        <Card title='创建个人影集作品' >
          <Form onSubmit={this.handleFormSubmit}>
            <Row gutter={24}>
              <FormFieldWrapper span={12} form={form} formFieldConfig={formFieldConfigs} />
            </Row>
            <Row>
              <span className={styles.text}>每一项前面标星号(*)为必填项 </span>
              <span className={styles.text}>文件上传最多上传 2 张图片或者视频 </span>
              <Col span={24} style={{ textAlign: 'right' }}>
                <Button type='primary' htmlType='submit'>提交</Button>
                <Button style={{ marginLeft: 8 }} onClick={this.handleFormCancel}>取消</Button>
              </Col>
            </Row>
          </Form>
        </Card>
        <Card title='以往个人图片影集' style={{ marginTop: 20 }}>
          {pictureList.length === 0 ? <Empty description='暂无数据' /> : this.renderOldPictureList(pictureList, 'image')}
        </Card>
        <Card title='以往个人视频影集' style={{ marginTop: 20 }}>
          {videoList.length === 0 ? <Empty description='暂无数据' /> : this.renderOldPictureList(videoList, 'video')}
        </Card>
      </div>
    )
  }

  private resetForm() {
    this.props.form.resetFields()
  }

  private async getStudentWorks() {
    const { data: { list } } = await this.api.getStudentDetailList(this.studentId)
    if (list.length === 0) {
      return
    }
    const pictureList = []
    const videoList = []
    for (const item of list) {
      const { picturePhotos, pictureVideos } = item
      const p = JSON.parse(picturePhotos) as string[]
      const v = JSON.parse(pictureVideos) as string[]
      pictureList.push(...(p.slice(0, 8)))
      videoList.push(...(v.slice(0, 8)))
      this.pictureList.push(...p)
      this.videoList.push(...v)
    }
    this.setState({ pictureList, videoList })
  }

  private renderOldPictureList(list: string[], type: 'video' | 'image') {
    return (
      <List
        grid={{ gutter: 4, column: 8 }}
        dataSource={list}
        pagination={this.getPaginationConfig()}
        renderItem={(item) => (
          <List.Item>
            <Card className={styles.pictureCard}>{
              type === 'image' ?
                <img src={`${configs.apiHost}${item}`} style={{ width: '100%' }} /> :
                <video src={`${configs.apiHost}${item}`} controls style={{ width: '100%', objectFit: 'cover' }} >
                  <source src={`${configs.apiHost}${item}`} type='video/mp4' />
                </video>
            }</Card>
          </List.Item>
        )}
      />
    )
  }

  private getPaginationConfig() {
    return {
      pageSize: 8,
    }
  }

  private handleFormSubmit(e: React.FormEvent) {
    e.stopPropagation()
    e.preventDefault()
    const { form } = this.props
    form.validateFields(async (err, values: ViewModels.CreateStudentWorks) => {
      if (err) {
        this.$message.error('请检查数据是否完整', 5)
        return
      }
      const { dspPicturePhotos, dspPictureVideos, evaluate } = values
      if (!dspPicturePhotos) {
        this.$message.error('请上传学生个人作品图片', 5)
        return
      }
      const picturePhotos = dspPicturePhotos.map((item) => {
        return item.response!.data.url
      })
      const pictureVideos = (dspPictureVideos || []).map((item) => {
        return item.response!.data.url
      })
      const { code, message } = await this.api.createStudentWorks(this.studentId,
        {
          evaluate,
          picturePhotos: JSON.stringify(picturePhotos),
          pictureVideos: JSON.stringify(pictureVideos)
        })
      if (code !== 0) {
        this.$message.error(message, 5)
        return
      }
      this.$message.success('创建成功', 5)
      await this.getStudentWorks()
      this.resetForm()
    })
  }

  private handleFormCancel() {
    const { history } = this.props
    history!.push('/student/list')
  }

}

export default Form.create<StudentDetailProps>({ name: 'detail_form' })(StudentDetail)
